import datetime
import uuid

from fastapi import APIRouter, HTTPException

from config.common_config import DATABASE_CONFIG
from models.request_models import SearchRequest, SearchResponse, SaveChatRequest, SaveChatResponse, SaveImgTextRequest, \
    SearchImgResponse, CommonResponse
from server.image_text_vac_server import ImageTextVacServer
from workflows.chatFlow import ChatFlow

router = APIRouter(prefix="/img/api/v1", tags=["chat"])

# 初始化组件
image_text_server =  ImageTextVacServer(
    host=DATABASE_CONFIG["HOST"],
    port=DATABASE_CONFIG["PORT"],
    user=DATABASE_CONFIG["USER"],
    pwd=DATABASE_CONFIG["PASSWORD"]
)
import logging

chatFlow = ChatFlow()

logger = logging.getLogger(__name__)

@router.post("/search_img_history", response_model=CommonResponse)
async def search_chat_history(request: SearchRequest):
    rId= str(uuid.uuid4())
    print("查询图片开始开始"+rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    try:
        logger.info("查询用户ID"+request.userId)

        records = image_text_server.search_records(request.userId,request.keyWord)
        if not records:
            return SearchResponse(chatHistory="没有找到相关聊天记录")

        img_history = []
        for r in records:
            res = SearchImgResponse(id=str(r["id"]), url=r["image_path"], describe=r["text_desc"])

            img_history.append(res)
        print("查询聊天开始" + rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        return CommonResponse(data= img_history)

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/test", response_model=SearchResponse)
async def test():
    rId = str(uuid.uuid4())
    print("查询图片开始开始" + rId + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    try:
        print("查询聊天开始" + rId + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        return SearchResponse(chatHistory="\n\n".join(rId))

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))




@router.post("/save_img_record", response_model=SaveChatResponse)
async def save_img_record(request: SaveImgTextRequest):
    rId = str(uuid.uuid4())
    print("新增开始" + rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    try:

        image_text_server.insert_record(request.url,request.discribe,request.userId,request.saasId)

        print("新增结束" + rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        return SaveChatResponse(
            status="success",
            recordId=rId

        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


